package belf.migrate.training;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 并行调用多个大模型，根据相同提示词生成不同的源端SQL
 */
@Slf4j
public class GenerateSourceSQL {
    private Map<String, List<String>> results = new HashMap<>();

    public void generate(String prompt) {
        int count = LlmDB.LLMs.size();
        long timestamp1 = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            Thread thread = new Thread(new LLMTask(
                    LlmDB.LLMs.get(i),
                    prompt,
                    latch));
            thread.start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long timestamp2 = System.currentTimeMillis();
        String seconds = String.format("%.2f seconds", (timestamp2-timestamp1)/1000.0);
//        log.debug("所有大模型查询完毕，总计花费时间{}秒", seconds);
    }

    public Map<String, List<String>> getResults() {
        return results;
    }

    private class LLMTask implements Runnable {
        private String llm;
        private String prompt;
        private CountDownLatch latch;
        List<String> sqls;


        public LLMTask(String llm, String prompt, CountDownLatch latch) {
            this.llm = llm;
            this.prompt = prompt;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
//                log.info("大模型{}开始执行", llm);
                sqls = LLMQueryTool.query(llm, prompt);
                results.put(llm, sqls);
//                log.info("{}输出的SQLs:\n{}", llm, String.join("\n", sqls));
            } finally {
                latch.countDown();
            }
        }
    }
}
